package com.seeyon.ctp.login.auth;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.LoginConstants;
import com.seeyon.ctp.login.AbstractLoginAuthentication;
import com.seeyon.ctp.login.LoginAuthenticationException;
import com.seeyon.ctp.organization.OrgConstants;
import com.seeyon.ctp.organization.principal.PrincipalManager;
import com.seeyon.kk.modules.ibatis.IbatisQueryDao;
import com.seeyon.kk.utils.IpUtil;

public class DefaultLoginAuthentication extends AbstractLoginAuthentication {

	private static final Logger LOGGER = Logger
			.getLogger(DefaultLoginAuthentication.class);

	private PrincipalManager principalManager = null;
	private IbatisQueryDao ibatisQueryDao = (IbatisQueryDao) AppContext.getBean("kkIbatisQueryDao");

	public DefaultLoginAuthentication() {
		if (principalManager == null) {
			principalManager = (PrincipalManager) AppContext
					.getBean("principalManager");
		}
	}

	@Override
	public String[] authenticate(HttpServletRequest request,
			HttpServletResponse response) throws LoginAuthenticationException {
		String username = request.getParameter(LoginConstants.USERNAME);// 用户名
		String password = request.getParameter(LoginConstants.PASSWORD);// 密码
		String[] IPconfigPool = null; // 存放通过登录名获取到的允许登录的ip地址
		Map<String, Object> query = new HashMap<String, Object>();
		
		if (username == null || password == null) {
			return null;
		}
		
		//通过用户名查询ip绑定数据如果没有查询到ip配置但是有用户名，则直接登录，如果有用户名并且配置有ip 做验证。
		String ip = IpUtil.getIpAddress(request);
		LOGGER.info("========= kk 追加ip登录限制 start !userName:" + username+ "--获取ip地址：" + ip);

		// 通过登录名查询该用户可以登录的ip地址进行匹配，如果匹配不到则返回为空
		query.put("loginName", username);

		try {
			List<Map<String, Object>> vl = getIbatisQueryDao().queryForList(
					"selectAllowedIPByloginName", query);
			if (vl.isEmpty()) {
				LOGGER.info("======根据登录名未查询到已启用的ip配置，登录名："+username);
				return null;
				}else{
					IPconfigPool = new String[vl.size() + 1];
					int index = 0;
					for (Iterator<Map<String, Object>> iterator = vl.iterator(); iterator
							.hasNext();) {
						Map<String, Object> vm = iterator.next();
						IPconfigPool[index] = MapUtils.getString(vm, "field0002");
						LOGGER.info("=========允许的ip地址:" + IPconfigPool[index]);
						++index;
				}
			}
		} catch (Exception e) {
			LOGGER.info("============kk.getIpByLoginName error! 消息：" + e);
		}
		//IPconfigPool = getIpByLoginName(username);
		if(!StringUtils.isBlank(IPconfigPool[0])){
			if (!ArrayUtils.contains(IPconfigPool, ip))
				return null;
		}
		LOGGER.info("========= kk 追加ip登录限制 登录 ：配置ip:["+Arrays.toString(IPconfigPool)+"]本地ip："+ip);
		// kk 追加ip登录限制 end
		// 开发模式不做
		if (AppContext.isRunningModeDevelop())
			return new String[] { username, password };
		else {
			try {
				if (principalManager.authenticate(username, password)) {
					return new String[] { username,
							OrgConstants.DEFAULT_INTERNAL_PASSWORD };
				}
			} catch (Exception e) {
				LOGGER.error("追加ip登录限制出错！", e);
			}

			return null;
		}
	}
	
	
	//需求更改不启用
	public String[] getIpByLoginName(String username) {
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("loginName", username);
		String[] ipA = null;
		try {
			List<Map<String, Object>> vl = getIbatisQueryDao().queryForList(
					"selectAllowedIPByloginName", query);
			if (!vl.isEmpty()) {
				ipA = new String[vl.size() + 1];
				int index = 0;
				for (Iterator<Map<String, Object>> iterator = vl.iterator(); iterator
						.hasNext();) {
					Map<String, Object> vm = iterator.next();
					ipA[index] = MapUtils.getString(vm, "field0002");
					LOGGER.info("=========允许的ip地址:" + ipA[index]);
					++index;
				}
			}
		} catch (Exception e) {
			LOGGER.info("============kk.getIpByLoginName error! 消息：" + e);
		}
		return ipA;
	}

	public IbatisQueryDao getIbatisQueryDao() {
		if (ibatisQueryDao == null) {
			ibatisQueryDao = (IbatisQueryDao) AppContext.getBean("kkIbatisQueryDao");
			LOGGER.info("==================ibatisQueryDao:"+ibatisQueryDao);
		}
		return ibatisQueryDao;
	}
}
